package manage

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"gozero-demo/internal/constants"
	"gozero-demo/internal/model/dao/model"
	"gozero-demo/internal/repo/mysql"
	"gozero-demo/internal/svc"
	"gozero-demo/internal/types"
)

type OrdersEditLogic struct {
	logx.Logger
	ctx        context.Context
	svcCtx     *svc.ServiceContext
	ordersRepo *mysql.OrdersRepo
}

// 创建和编辑订单
func NewOrdersEditLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrdersEditLogic {
	return &OrdersEditLogic{
		Logger:     logx.WithContext(ctx),
		ctx:        ctx,
		svcCtx:     svcCtx,
		ordersRepo: mysql.NewOrdersRepo(ctx, svcCtx),
	}
}

func (l *OrdersEditLogic) OrdersEdit(req *types.OrdersEditRequest) (resp *types.CommonResponse, err error) {
	//now := time.Now()
	//nowPtr := &now // 使用取地址操作符将 time.Time 转换为 *time.Tim

	// 构建需要插入的数据
	ordersData := &model.Orders{
		OrderNo:           "aaa1",
		GoodsNo:           req.GoodsNo,
		GoodsNameSnapshot: req.GoodsNameSnapshot,
		UserID:            100,
		Receiver:          req.Receiver,
		ContactPhone:      req.ContactPhone,
		Address:           req.Address,
		Status:            1,
		//PayTime:           nowPtr,
		PayPrice: int64(req.PayPrice * 100), //请求参数的单位是"元", 数据库中存储的是"分"
	}
	//fmt.Println("ordersData", utils.EchoJson(ordersData))

	if req.ID == 0 { //添加操作
		//todo 获取UserID
		ordersData.UserID = 100

		m, err := l.ordersRepo.CreateOrders(ordersData)
		if err != nil || m.ID == 0 {
			return types.ErrorResponse(constants.CodeUnknown.Code, err.Error(), l.ctx), nil
		}
	} else { //编辑操作
		_, err := l.ordersRepo.UpdateOrders(ordersData, req.ID)
		if err != nil {
			return types.ErrorResponse(constants.CodeUnknown.Code, err.Error(), l.ctx), nil
		}
	}

	return types.SuccessResponse(types.OrdersEditResponse{
		ID:      ordersData.ID,
		OrderNo: ordersData.OrderNo,
		GoodsNo: ordersData.GoodsNo,
		UserID:  ordersData.UserID,
	}, l.ctx), nil
}
